<template>
    <div>
        <Modal width="540" v-model="importModal" :mask-closable="false" :closable="false" class="import-modal">
            <div slot="header">
                {{ title }}
                <Icon class="f-fr" type="ios-close" @click="closeModal"/>
            </div>
            <Form :label-width="46" ref="importRef" :model="importMenber">
                <FormItem label="①">
                    <h6>下载模板，准备客户信息。一次最多导入1000条。</h6>
                    <Select v-model="selectedTemplateId" style="width:200px" transfer>
                        <Option
                            v-for="(item, index) in templateList"
                            :key="index"
                            :value="item.excelTemplateId"
                            :label="item.excelTemplateName"
                        >
                        </Option>
                    </Select>

                    <a @click="downloadTemplate" style="font-size:14px; margin-left: 10px;">
                        <Icon class="custom-icon-style" type="ios-download-outline"></Icon>
                        点击下载模板
                    </a>
                </FormItem>
                <FormItem label="②">
                    <h6>上传数据文件</h6>
                    <p>目前支持的文件类型为 *.xls，*.xlsx，*csv，文件4M。</p>
                    <Upload
                        ref="uploadExcel"
                        :before-upload="handleUpload"
                        :on-exceeded-size="handleMaxSize"
                        accept=".xls,.xlsx,.csv"
                        :format="['xls','xlsx','.csv']"
                        :max-size="4096"
                        action="/customs/business/importXlsBusiness"
                    >
                        <Button
                            size="small"
                            type="primary"
                            class="add-file-btn"
                            @click="addFileHandle"
                            :disabled="!selectedTemplateId"
                        >添加文件
                        </Button>
                        <br>
                        <span @click="removeFile" class="import-file-name">{{ importMenber.fileName }}</span>
                    </Upload>
                    <Progress
                        v-if="importMenber.ifUpload"
                        :percent="importMenber.uploadProgress"
                        :status="importMenber.uploadStatus"
                    >
                    </Progress>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button
                    type="default"
                    @click="closeModal"
                    :disabled="importMenber.uploadProgress!=0 && importMenber.uploadProgress!=100"
                >取消
                </Button>
                <Button
                    type="primary"
                    @click="importExcel"
                    :disabled="importMenber.file==null ||(importMenber.uploadProgress!=0 && importMenber.uploadProgress!=100)"
                >
                    {{importMenber.btnText}}
                </Button>
            </div>
        </Modal>

        <!--导入成功-->
        <Modal class-name="no-border" v-model="importSuccessModal" width="390" :closable="false" :mask-closable="false">
            <div slot="header">
                导入成功
                <Icon class="f-fr" type="ios-close" @click="importSuccessModal = false"/>
            </div>
            <div class="clearfix">
                <div class="f-fl icon">
                    <Icon type="ios-checkmark-circle"/>
                </div>
                <div class="f-fl modal-content">
                    导入完成
                </div>
            </div>
            <div slot="footer">
                <Button type="default" @click="showImportData">查看导入的数据</Button>
                <Button type="primary" @click="reImport">继续导入</Button>
            </div>
        </Modal>

        <!-- 导入失败 -->
        <Modal v-model="importFailureModal" width="746" class="col-2" :closable="false">
            <div slot="header">
                导入失败
                <Icon class="f-fr" type="ios-close" @click="importFailureModal = false"/>
            </div>
            <Table :columns="importErrorColumns" :data="importErrorTable"></Table>
            <div slot="footer">
                <Button type="default" @click="importFailureModal = false">取消</Button>
                <Button type="primary" @click="reImport">重新导入</Button>
            </div>
        </Modal>

        <!--错误提示-->  <!--适用于导入部分成功，需要展示导入不成功的原因-->
        <Modal v-model="importErrModal" width="746" class="col-2" :closable="false">
            <div slot="header">
                错误提示
                <Icon class="f-fr" type="ios-close" @click="importErrModal = false"/>
            </div>
            <Table :columns="importErrorColumns" :data="importErrorTable"></Table>
            <div slot="footer">
                <div slot="footer">
                    <Button type="default" @click="showImportData">查看导入的数据</Button>
                    <Button type="primary" @click="reImport">继续导入</Button>
                </div>
            </div>
        </Modal>
    </div>
</template>

<script>
import { downloadFile } from '@/api/fileManage.js'
import axios from '@/libs/api.request'

export default {
    name: 'ImportModal',

    data () {
        return {
            title: '导入客户',
            importModal: false,
            selectedTemplateId: -1,
            templateList: [
                {
                    excelTemplateId: -1,
                    excelTemplateName: '客户信息导入模板',
                    excelTemplateUrl: '/customs/customerManagement/downLoadCustInfoTemplate'
                }
            ],
            importMenber: {
                ifUpload: false,
                file: null,
                fileName: '',
                uploadProgress: 0,
                uploadStatus: 'normal',
                btnText: '导入'
            },
            importSuccessModal: false, // 导入成功
            importFailureModal: false, // 导入失败
            importErrorTable: [], // 导入失败列表
            importErrorColumns: [
                {
                    title: '行号',
                    key: 'rowNum',
                    width: 100,
                    align: 'center'
                },
                {
                    title: '错误描述',
                    key: 'msg',
                    align: 'center',
                    tooltip: true
                }
            ],
            importErrModal: false // 错误提示
        }
    },
    methods: {
        init () {
            this.importMenber.btnText = '导入'
            this.importModal = true
            this.importErrorTable = []
        },

        closeModal () {
            this.removeFile()
            this.importModal = false
        },

        addFileHandle () {
            this.removeFile()
        },

        // 删除文件
        removeFile () {
            this.importMenber.file = null
            this.importMenber.fileName = ''
            this.importMenber.ifUpload = false
            this.importMenber.uploadProgress = 0
            this.importMenber.uploadStatus = 'normal'
        },

        // 下载模板
        downloadTemplate () {
            if (!this.selectedTemplateId) {
                this.$Message.warning({
                    content: '请先选择下载模板',
                    duration: 3,
                    closable: true
                })
            } else {
                let url = ''
                this.templateList.forEach(item => {
                    if (this.selectedTemplateId === item.excelTemplateId) {
                        url = item.excelTemplateUrl
                    }
                })
                axios.request({
                    method: 'get',
                    url: url,
                    responseType: 'arraybuffer'
                }).then(res => {
                    if (res.status === 200) {
                        downloadFile(res, '客户信息导入模板')
                    }
                })
            }
        },

        handleUpload (file) {
            if (!/\.(xls|xlsx)$/.test(file.name)) {
                this.$Message.warning('文件 ' + file.name + ' 类型不正确')
                this.importMenber.file = null
                this.importMenber.fileName = ''
            } else if (file.size / 1024 > 5120) {
                this.$Message.warning('文件 ' + file.name + ' 大小不能超过4M')
                this.importMenber.file = null
                this.importMenber.fileName = ''
            } else {
                this.importMenber.btnText = '导入'
                this.importMenber.file = file
                this.importMenber.fileName = file.name
            }
            return false
        },

        handleMaxSize (file) {
            this.$Message.warning('文件 ' + file.name + ' 大小不能超过4M')
        },

        importExcel () {
            if (this.importMenber.btnText === '完成') {
                this.closeModal()
            } else {
                this.importMenber.uploadProgress = 0
                this.importMenber.uploadStatus = 'normal'
                let excelData = new FormData()
                excelData.append('file', this.importMenber.file)
                this.importMenber.ifUpload = true
                let progressTime = setInterval(() => {
                    if (this.importMenber.uploadProgress <= 70) {
                        this.importMenber.uploadProgress += 10
                        this.importMenber.uploadStatus = 'active'
                    }
                }, 300)
                this.importErrorTable = []
                const uploadUrl = this.selectedTemplateId === -1
                    ? '/customs/customerManagement/uploadCustFile'
                    : ('/excelTemplate/importXlsByTemplate?excelTemplateId=' + this.selectedTemplateId)
                axios.request({
                    method: 'post',
                    url: uploadUrl,
                    data: excelData
                }).then(res => {
                    clearInterval(progressTime)
                    if (res.data.code === '0000') { // 导入成功
                        this.importMenber.uploadProgress = 100
                        this.importMenber.uploadStatus = 'success'
                        this.importMenber.btnText = '完成'
                        if (Array.isArray(res.data.data) && res.data.data.length > 0) {
                            this.importErrModal = true
                            this.importErrorTable = res.data.data
                        } else {
                            this.importSuccessModal = true // 导入成功弹出框
                        }
                        this.$Message.success(res.data.msg)
                        this.$emit('reGetData') // 更新数据列表
                    } else { // 导入失败
                        this.importMenber.uploadProgress = 100
                        this.importMenber.uploadStatus = 'wrong'
                        if (Object.prototype.toString.call(res.data.data) === '[object Array]') {
                            this.importFailureModal = true
                            this.importErrorTable = res.data.data
                        } else {
                            this.$Message.warning(
                                {
                                    content: res.data.msg + '&nbsp;&nbsp;' + res.data.data,
                                    duration: 6,
                                    closable: true
                                }
                            )
                        }
                    }
                }, err => {
                    clearInterval(progressTime)
                    this.importMenber.uploadStatus = 'wrong'
                    this.$Message.error(err.message)
                })
            }
        },

        showImportData () {
            this.removeFile()
            this.importSuccessModal = false
            this.importModal = false
            this.importErrModal = false
        },

        reImport () {
            this.removeFile()
            this.importMenber.btnText = '导入'
            this.importSuccessModal = false
            this.importFailureModal = false
            this.importErrModal = false
        }

    } // methods end
}
</script>

<style lang="less">
    .import-modal {
        .add-file-btn {
            padding: 5px 18px;
            border-radius: 2px;
        }

        .custom-icon-style {
            font-size: 18px;
            font-weight: bold;
            vertical-align: -1px;
        }

        .import-file-name {
            cursor: pointer;
        }
    }
</style>
